package czk.concrent.juc.countDOwnLatch;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/7/25 14:42
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        // 创建计数器值
        CountDownLatch countDownLatch=new CountDownLatch(10);
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 模拟刺激战场网络加载
        // 定义数组存储每个玩家的加载状态
        String[] all=new String[10];
        // 定义随机数迷你延迟
        Random r=new Random();
        for (int j = 0; j < 10; j++) {
            // lambda只能引用局部常量，需要重新赋值
            int k=j;
            executorService.submit(()->{
                for (int i = 0; i <= 100; i++) {
                    try {
                        Thread.sleep(ThreadLocalRandom.current().nextInt(100));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    all[k]=i+"%";
                    // "\r“ 表示会覆盖前面打印结果
                    System.out.print("\r"+ Arrays.toString(all));
                }
                countDownLatch.countDown();
            });
        }
        // 主线程等待，都加载完成后再开始游戏
        countDownLatch.await();
        System.out.println();
        System.out.println("游戏开始");
        executorService.shutdown();
    }
}
